package org.misalen.web.server.filter;

import javax.servlet.http.HttpServletResponse;

import org.misalen.annotations.InterfaceApi;
import org.misalen.web.server.config.ServerResult;
import org.misalen.web.server.util.CustomerJsonSerializer;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

public class JsonReturnHandler implements HandlerMethodReturnValueHandler {

	@Override
	public boolean supportsReturnType(MethodParameter returnType) {
		boolean hasJsonAnno = returnType.getMethodAnnotation(InterfaceApi.class) != null;
		return hasJsonAnno;
	}

	@Override
	public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest) throws Exception {
		mavContainer.setRequestHandled(true);
		HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
		InterfaceApi annos = returnType.getMethodAnnotation(InterfaceApi.class);
		CustomerJsonSerializer jsonSerializer = new CustomerJsonSerializer();
		jsonSerializer.filter(annos.resultClass(), annos.include(), annos.filter());
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		String json = jsonSerializer.toJson(ServerResult.ok(returnValue));
		response.getWriter().write(json);
	}
}
